/*
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
*/

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) {
        vector<int> cur, next;
        if (!triangle.size()) return 0;
        cur.push_back(triangle[0][0]); // init sum
        for (int m = 1; m < triangle.size(); m++) {
            // cur.size() m , next.size() m+1, row m
            next.push_back(cur[0]+triangle[m][0]); // first elem
            for (int n = 1; n < m; n++) {
                next.push_back(triangle[m][n]+min(cur[n-1], cur[n]));
            }
            next.push_back(cur[m-1]+triangle[m][m]); // last elem
            swap(cur, next); next.clear();
        }
        int min = INT_MAX;
        for (auto it = cur.begin(); it != cur.end(); it++) {if (*it < min) min = *it;}
        return min;        
    }
};
